package initialize

import (
	"gitee.com/cdsailyj/go-vpn/common/core"
	"gitee.com/cdsailyj/go-vpn/global"
	"github.com/jmoiron/sqlx"
	go_ora "github.com/sijms/go-ora/v2"
	"gorm.io/gorm"
)

func GetDbDefault() *gorm.DB {
	return core.GetDb(global.CONFIG.Mysql, global.CONFIG.Mysql.Dsn, "mysql")
}

func GetPgsql() *gorm.DB {
	return core.GetDb(global.CONFIG.Pgsql, global.CONFIG.Pgsql.Dsn, "pgsql")
}

func GetSqlite() *gorm.DB {
	return core.GetDb(global.CONFIG.Sqlite, global.CONFIG.Sqlite.Dsn, "sqlite")
}

var xtkDb *sqlx.DB
var ywkDb *sqlx.DB

// 系统库
func GetXtkDB() (*sqlx.DB, error) {
	if xtkDb != nil {
		return xtkDb, nil
	}
	opt := map[string]string{}
	connStr := go_ora.BuildUrl(global.CONFIG.Xtk.Host, global.CONFIG.Xtk.Port, global.CONFIG.Xtk.Service, global.CONFIG.Xtk.Username, global.CONFIG.Xtk.Password, opt)
	db, err := sqlx.Open("oracle", connStr)
	if err != nil {
		return nil, err
	}
	err = db.Ping()
	if err != nil {
		return nil, err
	}
	db.SetMaxOpenConns(100)
	db.SetMaxIdleConns(5)

	xtkDb = db
	return xtkDb, err
}

// 业务库
func GetYwkDB() (*sqlx.DB, error) {
	if ywkDb != nil {
		return ywkDb, nil
	}
	opt := map[string]string{}
	connStr := go_ora.BuildUrl(global.CONFIG.Ywk.Host, global.CONFIG.Ywk.Port, global.CONFIG.Ywk.Service, global.CONFIG.Ywk.Username, global.CONFIG.Ywk.Password, opt)
	db, err := sqlx.Open("oracle", connStr)
	if err != nil {
		return nil, err
	}
	err = db.Ping()
	if err != nil {
		return nil, err
	}
	db.SetMaxOpenConns(100)
	db.SetMaxIdleConns(5)

	ywkDb = db
	return ywkDb, err
}

// 履职能力评估
func GetLznlptDB() (*sqlx.DB, error) {
	if ywkDb != nil {
		return ywkDb, nil
	}
	opt := map[string]string{}
	connStr := go_ora.BuildUrl(global.CONFIG.Lznlpt.Host, global.CONFIG.Lznlpt.Port, global.CONFIG.Lznlpt.Service, global.CONFIG.Lznlpt.Username, global.CONFIG.Lznlpt.Password, opt)
	db, err := sqlx.Open("oracle", connStr)
	if err != nil {
		return nil, err
	}
	err = db.Ping()
	if err != nil {
		return nil, err
	}
	db.SetMaxOpenConns(100)
	db.SetMaxIdleConns(5)

	ywkDb = db
	return ywkDb, err
}
